package com.zhj.micro.order.consumer;

import com.rabbitmq.client.Channel;
import com.zhj.micro.order.MicroOrderApplication;
import com.zhj.micro.order.entity.Order;
import com.zhj.micro.order.service.OrderService;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

import javax.annotation.Resource;

@Component
public class OrderConsumer {

    @Resource
    private OrderService orderService;

    @RabbitHandler
    @RabbitListener(queues = "delay_order_queue")
    public void process(Message message, Channel channel) {
        try {
            String orderId = new String(message.getBody());
            System.out.println("接收到订单检查订单状态：" + orderId);
            orderService.checkOrder(orderId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            System.out.println("数据处理失败");
        }
    }

    @RabbitHandler
    @RabbitListener(queues = "order_product_queue")
    public void processOrderProduct(Message message, Channel channel) {
        try {
            Order o = MicroOrderApplication.OBJECT_MAPPER.readValue(message.getBody(), Order.class);
            System.out.println("接收到库存扣减信息：" + o);
            orderService.updateOrderStatus(o.getOrderId(), Integer.valueOf(o.getOrderStatus()));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            System.out.println("数据处理失败");
        }
    }


    /**
     * 死信队列，监听到订单没有消费，直接修改为已经超时
     * @param message
     * @param channel
     */
    @RabbitHandler
    @RabbitListener(queues = "dlx_queue")
    public void dlxProcess(Message message, Channel channel) {
        try {
            Order o = MicroOrderApplication.OBJECT_MAPPER.readValue(message.getBody(), Order.class);
            System.out.println("订单超时：" + o.getOrderId());
            this.orderService.updateOrderStatus(o.getOrderId(), 4);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            System.out.println("数据处理失败");
        }
    }

}
